//
//  CZD_DetailOtherVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2020/9/27.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "CZD_DetailOtherVC.h"
#import "CZD_DetailHeadView.h"
#import "CaoZuoDanMainModel.h"
#import "CZD_OtherDetailYunDanCell.h"
#import "CZD_OtherDetailContentVC.h"
#import "LJInPutTool.h"
#import "CaoZuoDanQianShouVC.h"
#import "CZD_GoodBillListVC.h"

@interface CZD_DetailOtherVC () <UITableViewDelegate,UITableViewDataSource,ZJScrollPageViewDelegate> {
    NSString *current_ow_id;
}

@property (nonatomic, strong) CZD_DetailHeadView *headView;
@property (nonatomic, strong) CaoZuoDanMainModel *model;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) ZJSegmentStyle *menuStyle;//菜单栏
@property (nonatomic, strong) NSArray<NSString *> *titles;
@property (nonatomic, strong) ZJScrollPageView *scrollPageView;
@property (nonatomic, strong) UIView *scrollPageBGView;
@property (nonatomic, strong) UIButton *qianShouBtn;

@property (nonatomic, strong) LJInPutTool *inPutTool;//输入框

@end

@implementation CZD_DetailOtherVC

-(LJInPutTool *)inPutTool {
    if (!_inPutTool) {
        _inPutTool = [LJInPutTool new];
        __weak_self;
        _inPutTool.finishBlock = ^(NSString * _Nonnull str) {
            [weakself boHuiBill:str];
        };
    }
    return _inPutTool;
}

-(ZJScrollPageView *)scrollPageView {
    if (!_scrollPageView) {
        _scrollPageView = [[ZJScrollPageView alloc] initWithFrame:CGRectMake(0, self.headView.nim_bottom, ScreenW, ScreenH - NaviHeight - self.headView.height - self.bottomView.nim_height) segmentStyle:self.menuStyle titles:self.titles parentViewController:self delegate:self];
        _scrollPageView.hidden = YES;
    }
    return _scrollPageView;
}

-(UIView *)scrollPageBGView {
    if (!_scrollPageBGView) {
        _scrollPageBGView = [[UIView alloc] initWithFrame:CGRectMake(0, self.headView.nim_bottom, ScreenW, 40)];
        _scrollPageBGView.backgroundColor = [UIColor whiteColor];
        _scrollPageView.hidden = YES;
    }
    return _scrollPageBGView;
}

-(ZJSegmentStyle *)menuStyle {
    if (!_menuStyle) {
        _menuStyle = [ZJSegmentStyle new];
        _menuStyle.autoAdjustTitlesWidth = NO;
        _menuStyle.showLine = YES;//显示下划线
        _menuStyle.scrollTitle = YES;//设置标题栏可以滚动
        _menuStyle.segmentViewBounces = YES;//设置滚动标题栏有弹性
        _menuStyle.scaleTitle = YES;//设置选中标题缩放
        _menuStyle.scrollContentView = YES;//内容可以滑动
        _menuStyle.normalTitleColor = HexColor(0x9C9DB3);
        _menuStyle.selectedTitleColor = Color_ThemeColor;
        _menuStyle.scrollLineColor = Color_ThemeColor;
        _menuStyle.scrollLineWidth = 12;
        _menuStyle.segmentHeight = 40;
        _menuStyle.titleBigScale = 1.1;
        _menuStyle.titleFont = [UIFont systemFontOfSize:14];
    }
    return _menuStyle;
}

-(NSArray<NSString *> *)titles {
    if (!_titles) {
        _titles = @[];
    }
    return _titles;
}

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - BottomHeight - NaviHeight - 64, ScreenW, 64+BottomHeight)];
        _bottomView.backgroundColor = HexColor(0xffffff);
    }
    return _bottomView;
}

-(CaoZuoDanMainModel *)model {
    if (!_model) {
        _model = [CaoZuoDanMainModel new];
    }
    return _model;
}

-(CZD_DetailHeadView *)headView {
    if (!_headView) {
        _headView = [CZD_DetailHeadView new];
        _headView.frame = CGRectMake(0, 0, ScreenW, self.headView.height);
    }
    return _headView;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.headView.nim_bottom, ScreenW, ScreenH - NaviHeight - self.headView.height - self.bottomView.nim_height) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        __weak_self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakself requestForData];
        }];
        _tableView.hidden = YES;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"操作单详情";
    current_ow_id = @"";
    [self.view addSubview:self.headView];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.scrollPageBGView];
    [self.view addSubview:self.scrollPageView];
    [self requestForData];
}

- (void)requestForData {
    [HttpRequest PostWithApi:LogisticsSupplierCaoZuoDanQueryDetail params:@{@"o_id":self.o_id} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.model = [CaoZuoDanMainModel mj_objectWithKeyValues:responseObject];
            self.headView.model = self.model;
            [self configUI];
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)configUI {
    if (self.model.supplier_status == CaoZuoDanOperationStatusNoSure) {
        //
        self.tableView.hidden = NO;
        self.scrollPageView.hidden = YES;
        self.scrollPageBGView.hidden = YES;
        [self.bottomView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        UIButton *rejectBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, (self.bottomView.nim_width - 15 - 60) * 0.5, 44)];
        [rejectBtn setBackgroundColor:HexColor(0xF35959)];
        rejectBtn.layer.masksToBounds = YES;
        rejectBtn.layer.cornerRadius = 6;
        [rejectBtn setImage:[UIImage imageNamed:@"icon_reject"] forState:0];
        [rejectBtn setTitle:@"驳回" forState:0];
        [rejectBtn setTitleColor:HexColor(0xffffff) forState:0];
        rejectBtn.titleLabel.font = BoldFontOfSize(16);
        [rejectBtn addTarget:self action:@selector(rejectClick) forControlEvents:UIControlEventTouchUpInside];
        rejectBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
        [self.bottomView addSubview:rejectBtn];
        
        UIButton *passBtn = [[UIButton alloc] initWithFrame:CGRectMake(rejectBtn.nim_right + 15, 10, (self.bottomView.nim_width - 15 - 60) * 0.5, 44)];
        [passBtn setBackgroundColor:Color_ThemeColor];
        passBtn.layer.masksToBounds = YES;
        passBtn.layer.cornerRadius = 6;
        [passBtn setImage:[UIImage imageNamed:@"icon_adopt"] forState:0];
        [passBtn setTitle:@"通过" forState:0];
        [passBtn setTitleColor:HexColor(0xffffff) forState:0];
        passBtn.titleLabel.font = BoldFontOfSize(16);
        [passBtn addTarget:self action:@selector(passClick) forControlEvents:UIControlEventTouchUpInside];
        passBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
        [self.bottomView addSubview:passBtn];
    }else if (self.model.supplier_status == CaoZuoDanOperationStatusSure) {
        self.tableView.hidden = YES;
        self.scrollPageView.hidden = NO;
        self.scrollPageBGView.hidden = NO;
        [self.bottomView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        self.qianShouBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, self.bottomView.nim_width - 60, 44)];
        [self.qianShouBtn setBackgroundColor:Color_ThemeColor];
        self.qianShouBtn.layer.masksToBounds = YES;
        self.qianShouBtn.layer.cornerRadius = 6;
        [self.qianShouBtn setImage:[UIImage imageNamed:@"icon_adopt"] forState:0];
        [self.qianShouBtn setTitle:@"一键签收" forState:0];
        [self.qianShouBtn setTitleColor:HexColor(0xffffff) forState:0];
        self.qianShouBtn.titleLabel.font = BoldFontOfSize(16);
        [self.qianShouBtn addTarget:self action:@selector(qianShouClick) forControlEvents:UIControlEventTouchUpInside];
        self.qianShouBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
        [self.bottomView addSubview:self.qianShouBtn];
        
        [self requestForLineCount];
    }
}

//确认状态下请求有几条线路
- (void)requestForLineCount {
    [HttpRequest PostWithApi:LogisticsSupplierCaoZuoDanQueryDetailLineCount params:@{@"o_id":self.o_id} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            NSMutableArray *mut = [NSMutableArray array];
            NSArray *arr = (NSArray *)responseObject;
            [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [mut addObject:[NSString stringWithFormat:@"线路%@",[obj objectForKey:@"ow_id"]]];
            }];
            self.titles = mut;
            [self.scrollPageView reloadWithNewTitles:self.titles];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

//一键签收
- (void)qianShouClick {
    CaoZuoDanQianShouVC *vc = [CaoZuoDanQianShouVC new];
    vc.o_id = self.o_id;
    vc.ow_id = current_ow_id;
    vc.titleStr = self.model.type == CaoZuoDanSupplierTypeGanXian ? @"干线签收" : @"派送签收";
    [self.rt_navigationController pushViewController:vc animated:YES];
}

//驳回
- (void)rejectClick {
    self.inPutTool.placeholder = @"请输入驳回原因";
    self.inPutTool.sureBtnText = @"确认驳回";
    self.inPutTool.cancleBtnText = @"取消驳回";
    [self.inPutTool showInView:MAIN_WINDOW];
}

- (void)boHuiBill:(NSString *)str {
    [HttpRequest PostWithApi:LogisticsSupplierCaoZuoDanSure params:@{@"o_id":self.o_id,@"type":@(3),@"reject_remarks":str} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            __weak_self;
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"驳回成功" delayOperation:^{
                [weakself.rt_navigationController popViewControllerAnimated:YES];
            }];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshCaoZuoDanList object:nil];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

//通过
- (void)passClick {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定通过？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestForPass];
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:sureAction];
    [alert addAction:cancleAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)requestForPass {
    [HttpRequest PostWithApi:LogisticsSupplierCaoZuoDanSure params:@{@"o_id":self.o_id,@"type":@(2)} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            __weak_self;
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"确认成功" delayOperation:^{
                [weakself requestForData];
            }];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshCaoZuoDanList object:nil];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.model.wallbill_list.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CZD_OtherDetailYunDanCell *cell = [CZD_OtherDetailYunDanCell CZD_OtherDetailYunDanCellWithTableView:tableView];
    CaoZuoDanYunDanModel *model = self.model.wallbill_list[indexPath.row];
    cell.model = model;
    __weak_self;
    cell.goodListBlock = ^{
        CZD_GoodBillListVC *vc = [CZD_GoodBillListVC new];
        vc.wa_id = model.wa_id;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CZD_OtherDetailYunDanCell *cell = [CZD_OtherDetailYunDanCell CZD_OtherDetailYunDanCellWithTableView:tableView];
    CaoZuoDanYunDanModel *model = self.model.wallbill_list[indexPath.row];
    cell.model = model;
    return cell.height;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = Color_backgroundColor;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (NSInteger)numberOfChildViewControllers {
    return self.titles.count;
}

- (UIViewController<ZJScrollPageViewChildVcDelegate> *)childViewController:(UIViewController<ZJScrollPageViewChildVcDelegate> *)reuseViewController forIndex:(NSInteger)index {
    CZD_OtherDetailContentVC<ZJScrollPageViewChildVcDelegate> * childVC = (CZD_OtherDetailContentVC *)reuseViewController;
    CZD_OtherDetailContentVC *vc = [CZD_OtherDetailContentVC new];
    childVC = vc;
    vc.o_id = self.o_id;
    if ([self.titles[index] containsString:@"线路"]) {
        NSMutableString *str = [NSMutableString stringWithString:self.titles[index]];
        [str deleteCharactersInRange:NSMakeRange(0,2)];
        vc.ow_id = str;
    }
    __weak_self;
    vc.refreshBtnBlock = ^(CaoZuoDanSignType status) {
        __strong_self;
        strongSelf->current_ow_id = vc.ow_id;
        if (status == CaoZuoDanSignTypeNoShow) {
            strongSelf.qianShouBtn.userInteractionEnabled = NO;
            [strongSelf.qianShouBtn setBackgroundColor:HexColor(0xCCCCD9)];
            [strongSelf.qianShouBtn setImage:[UIImage imageNamed:@""] forState:0];
            [strongSelf.qianShouBtn setTitle:@"请等待上一个供应商签收" forState:0];
            strongSelf.qianShouBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        }else if (status == CaoZuoDanSignTypeShow) {
            strongSelf.qianShouBtn.userInteractionEnabled = YES;
            [strongSelf.qianShouBtn setBackgroundColor:Color_ThemeColor];
            [strongSelf.qianShouBtn setImage:[UIImage imageNamed:@"icon_adopt"] forState:0];
            [strongSelf.qianShouBtn setTitle:@"一键签收" forState:0];
            strongSelf.qianShouBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
        }else if (status == CaoZuoDanSignTypeZhiHui) {
            strongSelf.qianShouBtn.userInteractionEnabled = NO;
            [strongSelf.qianShouBtn setBackgroundColor:HexColor(0xCCCCD9)];
            [strongSelf.qianShouBtn setImage:[UIImage imageNamed:@"icon_adopt"] forState:0];
            [strongSelf.qianShouBtn setTitle:@"已签收" forState:0];
            strongSelf.qianShouBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
        }
    };
    return childVC;
}

//子控制器实现完整生命周期
- (BOOL)shouldAutomaticallyForwardAppearanceMethods {
    return NO;
}

@end
